<template>
  <div class="card filter">
    <!-- <div>
      <div class="center-group">
        <div class="content">
          <div class="navbar-btn" :class="{active: typetab === type.id}" v-for="type in typeList" :key="type.id">
            <a @click="typetab = type.id">{{type.label}}</a>
          </div>
        </div>
      </div>
    </div> -->
    <div class="search">
      <el-input v-model="filterText" placeholder="输入关键字进行过滤" clearable >
        <template #prefix>
          <i-ep-search />
        </template>
      </el-input>
      <!-- <el-dropdown trigger="click">
        <el-icon size="20"><More /></el-icon>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="toggleTreeNodes(true)">展开全部</el-dropdown-item>
            <el-dropdown-item @click="toggleTreeNodes(false)">折叠全部</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown> -->
    </div>
    <el-scrollbar style="height: calc(100% - 95px);">
      <!-- :data="multiple ? treeData : treeAllData" -->
      <el-tree
        ref="treeRef"
        :load="loadNode"
        lazy
        node-key="id"
        :show-checkbox="multiple"
        :check-strictly="false"
        :current-node-key="!multiple ? selected : ''"
        :highlight-current="!multiple"
        :expand-on-click-node="false"
        :check-on-click-node="multiple"
        :props="defaultProps"
        :filter-node-method="filterNode"
        :default-checked-keys="multiple ? selected : []"
        @node-click="handleNodeClick"
        @check="handleCheckChange"
      >
        <template #default="scope">
          <span class="el-tree-node__label">
            <!-- <slot :row="scope"> -->
            <span>{{ scope.node.label }}</span>
            <!-- </slot> -->
            <span>
              <ToolBar
                :data="scope"
                limit="1"
                type="list"
                :tools="getToolConfig(scope.node.data)"
                :tool-width="50"
                @click="handleClick"
              />
            </span>
          </span>
        </template>
      </el-tree>
      <a class="add-btn" @click="onModify">
        <i-ep-plus class="mr-tiny" />新建{{typetab==='org'?'机构':'班级'}}
      </a>
    </el-scrollbar>

    <OrgModify
      :type="modifyType"
      :visible="showOrgModify"
      :spaceDetail="questionInfo"
      @on-close-codify="onCloseModify"
    />
  </div>
</template>

<script setup lang="ts" name="TreeFilter">
import { ref, watch, onBeforeMount, nextTick } from "vue";
import { getOrgStructure } from '@/management/api/basedata'
import { ORGTREE_TYPE } from '@/management/utils/constant.ts'

import { ElTree } from "element-plus";
import ToolBar from './ToolBar.vue'
import OrgModify from './OrgModify.vue'

// 接收父组件参数并设置默认值
interface TreeFilterProps {
  multiple?: boolean; // 是否为多选 ==> 非必传，默认为 false
  defaultValue?: any; // 默认选中的值 ==> 非必传
}
const props = withDefaults(defineProps<TreeFilterProps>(), {
  id: "id",
  label: "label",
  multiple: false
});

const defaultProps = {
  id: "id",
  children: "children",
  label: "name"
};

const treeRef = ref<InstanceType<typeof ElTree>>();
const treeData = ref<{ [key: string]: any }[]>([]);
const treeAllData = ref<{ [key: string]: any }[]>([]);

const selected = ref();
const typetab = ref('org');
// const typeList = ref([{ id: "org", label: "组织" }, { id: "cls", label: "班级" }]);
const modifyType = ref('')
const questionInfo = ref({})
const showOrgModify = ref(false)
const setSelected = () => {
  if (props.multiple) selected.value = Array.isArray(props.defaultValue) ? props.defaultValue : [props.defaultValue];
  else selected.value = typeof props.defaultValue === "string" ? props.defaultValue : "";
};
const getToolConfig = (row: any) => {
  let funcList = [{
      key: 'edit',
      label: '编辑'
    },
    {
      key: 'delete',
      label: '删除',
      icon: 'icon-shanchu'
    }]

  switch (row?.type) {
    case ORGTREE_TYPE.REGION:
      funcList = funcList.concat([{
        key: 'addorg',
        label: '添加子机构',
        icon: 'icon-shanchu'
      }])
      return funcList
    case ORGTREE_TYPE.REGION_EDU:
      funcList = funcList.concat([{
        key: 'addorg',
        label: '添加子机构',
        icon: 'icon-shanchu'
      }])
      return funcList
    case ORGTREE_TYPE.SCHOOL:
      funcList = funcList.concat([{
        key: 'adddepart',
        label: '添加学校',
        icon: 'icon-shanchu'
      }])
      return funcList
    case ORGTREE_TYPE.SCHOOL_EDU:
      funcList = funcList.concat([{
        key: 'addorg',
        label: '添加子机构',
        icon: 'icon-shanchu'
      }, {
        key: 'addschool',
        label: '添加学校',
        icon: 'icon-shanchu'
      }])
      return funcList
    case ORGTREE_TYPE.PROVINCE_EDU:
      funcList = funcList.concat([{
        key: 'addorg',
        label: '添加子机构',
        icon: 'icon-shanchu'
      }, {
        key: 'addschool',
        label: '添加学校',
        icon: 'icon-shanchu'
      }])
      return funcList
    case ORGTREE_TYPE.GROUP_SCHOOL:
      funcList = funcList.concat([{
        key: 'addschool',
        label: '添加学校',
        icon: 'icon-shanchu'
      }])
      return funcList
    case ORGTREE_TYPE.OFFICE_ORG:
      funcList = funcList.concat([{
        key: 'adddepart',
        label: '添加部门',
        icon: 'icon-shanchu'
      }])
      return funcList
    case ORGTREE_TYPE.OFFICE_ORG_NODE:
      funcList = funcList.concat([{
        key: 'adddepart',
        label: '添加组织',
        icon: 'icon-shanchu'
      }])
      return funcList
    case ORGTREE_TYPE.TEACH_ORG:
      funcList = []
      return funcList
    case ORGTREE_TYPE.SECTION:
      funcList = []
      return funcList
    case ORGTREE_TYPE.ORG_CLASS:
      funcList = []
      return funcList
    case ORGTREE_TYPE.TEACH_CLASS:
      funcList = []
      return funcList
    case ORGTREE_TYPE.GRADE:
      funcList = [{
        key: 'addclass',
        label: '添加班级',
        icon: 'icon-shanchu'
      }]
      return funcList
    case ORGTREE_TYPE.CLASS:
      funcList = [{
        key: 'addstudent',
        label: '添加学生',
        icon: 'icon-shanchu'
      }]
      return funcList
    default:
      return funcList
  }

}
const handleClick = (key: any, data: any) => {
  console.log(key, data)
  switch (key) {
    // case QOP_MAP.EDIT:
    //   onModify(data, QOP_MAP.EDIT)
    //   return
    // case QOP_MAP.COPY:
    //   onCopy(data, QOP_MAP.COPY)
    //   return
    // case 'analysis':
    //   router.push({
    //     name: 'FormsPublishAnalysis',
    //     params: {
    //       id: data._id
    //     }
    //   })
    //   return
    // case 'release':
    //   onPublish(data)
    //   return
    // case 'delete':
    //   onDelete(data)
    //   return
    // case 'recover':
    //   onRecover(data)
    //   return
    // case 'delforever':
    //   onDelforever(data)
    //   return
    // case 'collect':
    //   onCollect(data)
    //   return
    // case 'uncollect':
    //   onUnCollect(data)
    //   return
    default:
      return
  }
}
const onModify = (data: any, type: any) => {
  showOrgModify.value = true
  modifyType.value = type
  questionInfo.value = data
}
const onCloseModify = (type: any) => {
  showOrgModify.value = false
  questionInfo.value = {}
}

const loadNode = async (node: any, resolve: any) => {
  let params = {}
  if (node.level === 0) {
    params = {
      id: '-1',
      type: '-1',
      orgId: (window as any).$app.user.orgId
    }
  } else {
    params = {
      id: node.data.id,
      type: node.data.type,
      orgId: (window as any).$app.user.orgId
    }
  }

  const res: any = await getOrgStructure(params);
  if (res?.serverResult?.resultCode === '200') {
    return resolve((res?.pageInfo?.list || []).map((item: any) => {
      return {
        ...item,
        isLeaf: !item.type || item.type === ORGTREE_TYPE.CLASS
      };
    }));
  } else {
    return resolve([]);
  }
}

onBeforeMount(async () => {
  setSelected();
  // if (props.requestApi) {
  //   const { data } = await props.requestApi!();
  //   treeData.value = data;
  //   treeAllData.value = [{ id: "", label: "全部", isLeaf: true }, ...data];
  // }
});

// 使用 nextTick 防止打包后赋值不生效，开发环境是正常的
watch(
  () => props.defaultValue,
  () => nextTick(() => setSelected()),
  { deep: true, immediate: true }
);

const filterText = ref("");
watch(filterText, val => {
  treeRef.value!.filter(val);
});

// 过滤
const filterNode = (value: string, data: { [key: string]: any }, node: any) => {
  if (!value) return true;
  let parentNode = node.parent,
    labels = [node.label],
    level = 1;
  while (level < node.level) {
    labels = [...labels, parentNode.label];
    parentNode = parentNode.parent;
    level++;
  }
  return labels.some(label => label.indexOf(value) !== -1);
};

// 切换树节点的展开或折叠状态
const toggleTreeNodes = (isExpand: boolean) => {
  let nodes = treeRef.value?.store.nodesMap;
  console.log(nodes);
  if (!nodes) return;
  for (const node in nodes) {
    if (nodes.hasOwnProperty(node)) {
      nodes[node].expanded = isExpand;
    }
  }
};

// emit
const emit = defineEmits<{
  change: [value: any];
}>();

// 单选
const handleNodeClick = (data: { [key: string]: any }) => {
  if (props.multiple) return;
  emit("change", data);
};

// 多选
const handleCheckChange = () => {
  emit("change", treeRef.value?.getCheckedKeys());
};

// 暴露给父组件使用
defineExpose({ treeData, treeAllData, treeRef });
</script>

<style scoped lang="scss">
.card {
  box-sizing: border-box;
  padding: 20px;
  overflow-x: hidden;
  background-color: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.05);
}
.filter {
  box-sizing: border-box;
  width: 320px;
  height: 100%;
  padding: 18px;
  margin-right: 10px;
  // .title {
  //   margin: 0 0 15px;
  //   font-size: 18px;
  //   font-weight: bold;
  //   color: var(--el-color-info-dark-2);
  //   letter-spacing: 0.5px;
  // }
  .search {
    display: flex;
    align-items: center;
    margin: 10px 0 15px;
    .el-icon {
      cursor: pointer;
      transform: rotate(90deg) translateY(-8px);
    }
  }
  .el-scrollbar {
    :deep(.el-scrollbar__wrap) {
      height: 100%;
    }
    :deep(.el-scrollbar__view) {
      height: 100%;
    }
    
    :deep(.el-tree) {
      max-height: calc(100% - 20px);
      overflow: auto;
      .el-tree-node__content {
        height: 42px;
      }
      .el-tree-node__label {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
      }
    }
    :deep(.el-tree--highlight-current) {
      .el-tree-node.is-current > .el-tree-node__content {
        // background-color: var(--el-color-primary);
        color: var(--el-color-primary);
        border-radius: 4px;
        .el-tree-node__label,
        .el-tree-node__expand-icon {
          color: var(--el-color-primary);
        }
        .is-leaf {
          color: transparent;
        }
      }
    }
  }

  .center-group {
    flex: 1;
    justify-content: center;
    height: 32px;
    border-bottom: 1px solid var(--el-border-color-light);

    .content {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .content .navbar-btn {
      color: var(--el-menu-text-color);
      position: relative;
      padding: 0 20px;
      cursor: pointer;
    }
    .content .navbar-btn.active {
      color: var(--el-color-primary);
    }
    .content .navbar-btn.active::before {
      content: "";
      position: absolute;
      width: 30px;
      height: 3px;
      background-color: var(--el-color-primary);
      bottom: -12px;
      left: 20px;
    }
  }
}
.add-btn {
  margin-top: 10px;
  padding: 8px 10px;
  display: flex;
  justify-content: center;
  align-content: center;
  line-height: 18px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  cursor: pointer;
  color: var(--el-menu-text-color);
  background-color: var(--el-bg-color);

  &:hover {
    color: var(--el-color-primary);
    border-color: var(--el-bg-color-light);
  }
}
</style>
